#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
import time
from functools import wraps
from typing import Callable, TypeVar, cast

import jwt
from flask import request

from flask import jsonify

T = TypeVar("T", bound=Callable)  # pylint: disable=invalid-name


def exception_handle(function: T):
    """Decorator for functions that require authentication"""

    @wraps(function)
    def decorated(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except Exception as e:
            return jsonify(code=500, message=str(e), data=None)

    return cast(T, decorated)


def provide_user(func: Callable[..., T]) -> Callable[..., T]:

    @wraps(func)
    def wrapper(*args, **kwargs) -> T:
        token = request.headers.get("Authorization", type=str, default=None)
        if token is None:
            return jsonify(code=401, message="accredit error,", data=None)

        jwt_decoder = jwt.decode(token, "kDAmTU2p9E83xw5zzdk9mw", algorithm="HS512")
        use_name = jwt_decoder["username"]
        return func(*args, oa_user_name=use_name, **kwargs)
    return wrapper
